package org.news.web.utils;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.ReUtil;
import org.apache.http.entity.ContentType;
import org.apache.tomcat.util.http.fileupload.ByteArrayOutputStream;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.UUID;

public class FileUtils {





    public static MultipartFile UrlToMultpartFile(String coverUrl){
        try {
            if(coverUrl == null){
                return null;
            }
            coverUrl = coverUrl.replaceAll("^\\W+","");
            coverUrl = coverUrl.replaceAll("\\W+$","");
            coverUrl = ReUtil.get("(http.*[a-zA-Z]$)",coverUrl,0);
            if(coverUrl == null){
                return null;
            }
            System.out.println(coverUrl);

            String fiex = coverUrl.substring(coverUrl.lastIndexOf(".")+1,coverUrl.lastIndexOf(".")+4);
            URL url = new URL(coverUrl);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setConnectTimeout(10*1000);
            final ByteArrayOutputStream output = new ByteArrayOutputStream();
            IOUtils.copy(urlConnection.getInputStream(),output);
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(output.toByteArray());

            String fileName = RandomUtil.randomString(10)+"."+fiex;

            MockMultipartFile mockMultipartFile = new MockMultipartFile(fileName,fileName, ContentType.APPLICATION_OCTET_STREAM.toString(),byteArrayInputStream);
            return mockMultipartFile;
        } catch (MalformedURLException e) {
            return null;
        } catch (IOException e) {
            return null;
        }
    }
}
